/**  
 * @date 2023-11-24 
 * @author Zhang Yu
 */
package com.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author gblfy
 * @Description https://www.gblfy.com
 * @Date 2019/12/8 15:45
 */
@RestController
public class LoginController {

	/**
	 * 登录方法
	 *
	 * @param username
	 * @param password
	 */
	@PostMapping("/doLogin")
	public String doLogin(String username, String password) {
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(new UsernamePasswordToken(username, password));
			return "登录成功!";
		} catch (AuthenticationException e) {
			e.printStackTrace();
			return "登录失败!";
		}
	}

	/**
	 * 测试方法
	 *
	 * @return
	 */
	@GetMapping("/hello")
	public String helloWord() {
		return "helloWord";
	}

	/**
     * 未授权方法
     *
     * @return
     */
	@GetMapping("/unauthorizedurl")
	public String unauthorizedurl() {
		return "unauthorizedurl";
	}
	
	/**
     * 未授权测试方法
     *
     * @return
     */
	@RequiresRoles("admin")
	@GetMapping("/admin/role")
	public String unauth() {
		return "需要admin权限";
	}

	/**
	 * 统一拦截登录页面
	 *
	 * @return
	 */
	@GetMapping("/login")
	public String login() {
		return "please login!";
	}
	
    @GetMapping("/logout")
    public String logout() {
        // 执行登出
        SecurityUtils.getSubject().logout();
        // 重定向到登录页面
        return "请重新登录";
    }
}